package com.anzhen.domain.web;

import com.alibaba.fastjson.JSON;
import com.anzhen.domain.entity.TodoRecord;
import com.anzhen.domain.enumType.ResponseStatus;
import com.anzhen.domain.enumType.TodoStatus;
import com.anzhen.domain.service.TodoService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

/**
 * Created by anzhen on 2017-6-19.
 */
@RestController
public class Controller {
	Logger logger = LoggerFactory.getLogger(getClass());

	@Autowired
	private TodoService todoService;

	@RequestMapping(value = "add")
	public Response add(int uId, String content) {
		TodoRecord todoRecord = new TodoRecord();
		todoRecord.setuId(uId);
		todoRecord.setTdContent(content);
		todoService.addTodoRecord(todoRecord);
		Response response = new Response(ResponseStatus.SUCCESS, "添加成功", null);
		logger.info("uId:{} content:{} response:{}", uId, content, JSON.toJSON(response));
		return response;
	}

	@RequestMapping(value = "getTodo")
	public Response getTodo(String email, TodoStatus todoStatus) {
		Response response = new Response(ResponseStatus.SUCCESS, "查询成功", todoService.getTodoList(email, todoStatus));
		logger.info("uId:{} todoStatus:{} response:{}", email, todoStatus, JSON.toJSON(response));
		return response;
	}

	@RequestMapping(value = "completeTodo")
	public Response completeTodo(int todo) {
		todoService.completeTodo(todo);
		Response response = new Response(ResponseStatus.SUCCESS, "修改成功", null);
		logger.info("todo:{} response:{}", todo, JSON.toJSON(response));
		return response;
	}

	@RequestMapping(value = "exception")
	public Response exception(int todo) {
		if (todo > 0) {
			throw new RuntimeException("exception");
		}
		return null;
	}

	@ExceptionHandler(value=Throwable.class)
	public Response handleException(Exception exception, HttpServletRequest request) {
		logger.error("系统异常!", exception);
		return new Response(ResponseStatus.FAIL, exception.getMessage(), null);
	}

}
